package com.bocai.kelala.ui.travel.main.act;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bocai.kelala.App;
import com.bocai.kelala.R;
import com.bocai.kelala.base.BaseActivity;
import com.bocai.kelala.bean.MainListBean;
import com.bocai.kelala.bean.PhoneTypeBean;
import com.bocai.kelala.bean.UserBean;
import com.bocai.kelala.ui.travel.main.ada.MainAdapter;
import com.bocai.kelala.ui.travel.main.contract.MainContract;
import com.bocai.kelala.ui.travel.main.module.MainModule;
import com.bocai.kelala.ui.travel.main.presenter.MainPresenter;
import com.bocai.kelala.ui.travel.set.act.CertificationInformationActivity;
import com.bocai.kelala.ui.travel.set.act.CertificationInformationStateActivity;
import com.bocai.kelala.ui.travel.stroke.act.PublishStrokeAddressActivity;
import com.bocai.kelala.util.AESUtils;
import com.bocai.kelala.util.SP;
import com.bocai.kelala.util.ToastUitl;
import com.bocai.kelala.widget.LoginDialog;
import com.bocai.kelala.widget.UserPopupWindow;
import com.bocai.mybase.base.BaseRecyclerAdapter;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Set;

import javax.inject.Inject;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by yuanfei on 2017/6/6.
 */

public class MainActivity extends BaseActivity implements MainContract.view,View.OnClickListener,XRecyclerView.LoadingListener {


    @BindView(R.id.personal)
    LinearLayout personal;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.btn_select)
    Button btnSelect;
    @BindView(R.id.xrecycle)
    XRecyclerView xrecycle;
    @BindView(R.id.pub_img)
    ImageView pubImg;
    @BindView(R.id.ll_pub)
    LinearLayout llPub;
    MainAdapter mainAdapter;
    boolean isShow = true;
    Animation outAnimation;
    Animation inAnimation;
    LoginDialog loginDialog;
    @Inject
    MainPresenter presenter;

    private int index = 0;

    private int pageIndex = 1;

    private int login = 0;

    @Override
    public int getLayoutId() {
        return R.layout.main;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new MainModule(this)).inject(this);
    }

    @Override
    public void initView() {
        initToolbar("客拉拉旅行社端");
        index = getIntent().getIntExtra("index",0);

        loginDialog = new LoginDialog(this).builder().setTitle("登录").setConfirmButton("下一步");
        loginDialog.setPresenter(presenter);
        xrecycle.setLayoutManager(new LinearLayoutManager(this));
        mainAdapter = new MainAdapter();
        xrecycle.setAdapter(mainAdapter);
        outAnimation = AnimationUtils.loadAnimation(this,R.anim.fab_out);
        inAnimation = AnimationUtils.loadAnimation(this,R.anim.fab_in);

//        userPopupWindow = new UserPopupWindow(this,presenter);
//        if (!SP.get(mContext,"id","").toString().equals("")){
//            userPopupWindow.setData();
//        }
        personal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!SP.get(mContext,"id","").toString().equals("")){
//                    userPopupWindow.getUser();
//                    userPopupWindow.showAsDropDown(findViewById(R.id.top_line),  0, 0);

                    startActivity(UserActivity.class);
                    overridePendingTransition(R.anim.user_open, R.anim.without);
                }else{
                    setDialog();
                }
            }
        });
        btnSelect.setOnClickListener(this);
        pubImg.setOnClickListener(this);

        llPub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("setOnClickListener","setOnClickListener");
            }
        });

        xrecycle.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                Log.e("dy",dy+"");
                if (dy > 5 &&isShow){
                    isShow = false;
                    setAnimOut();
                }
                if (dy < -5 && !isShow){
                    isShow = true;
                    setAnimIn();
                }
            }
        });
        mainAdapter.setOnItemOnListener(new BaseRecyclerAdapter.OnItemClickedListener() {
            @Override
            public void onItemClicked(int id, int index) {
                if (TextUtils.isEmpty(SP.get(MainActivity.this,"id","").toString())){
                    setDialog();
//                    showErrorTip("请先登录");
                }else {
                    startActivityForResult(new Intent(MainActivity.this, VehicleDetailActivity.class).putExtra("orderId", mainAdapter.getDataList().get(index).getOrderId()),27);
                }
            }
        });
        xrecycle.setLoadingListener(this);
//        xrecycle.refresh();
        llRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(SP.get(MainActivity.this,"id","").toString())){
                    setDialog();
//                    showErrorTip("请先登录");
                }else {
                    startActivity(MessageActivity.class);
                }
            }
        });
        if (index == 1){
            setDialog();
        }
    }

    @Override
    public void showLoading(String title) {

        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {
        if (msg.equals("用户授权失败")){
            msg = "您的登录已失效，请重新登录";
            setDialog();
        }else if (msg.equals("网络异常")){
            xrecycle.refreshComplete();
            xrecycle.loadMoreComplete();
        }else if (msg.equals("非法手机号")){
            loginDialog.setEnterPhone();
        }
        showShortToast(msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_select:

                startActivity(SelectActivity.class);
                break;
            case R.id.pub_img:

                if (TextUtils.isEmpty(SP.get(MainActivity.this,"id","").toString())){
//                    showErrorTip("请先登录");
                    setDialog();
                } else if ((int) SP.get(this, "ApprovalStatus", 0) == 0) {
                        startActivity(new Intent(this, CertificationInformationActivity.class));
                } else if ((int) SP.get(this, "ApprovalStatus", 0) == -1) {
                        startActivity(new Intent(this, CertificationInformationStateActivity.class));
                } else if ((int) SP.get(this, "ApprovalStatus", 0) == 1) {
                    login = 1;
                    presenter.getUser();
                }else {
                    startActivity(PublishStrokeAddressActivity.class);
                }
                break;
        }
    }

//    public void setAnimOut() {
//        ObjectAnimator anim = ObjectAnimator//
//                .ofFloat(pubImg, "yuan", 1.0F, 0.0F)//
//                .setDuration(500);//
//        anim.start();
//        final int height = pubImg.getTop();
//        Log.e("height",height+"");
//        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//                float cVal = (Float) animation.getAnimatedValue();
//                pubImg.setAlpha(cVal);
//                pubImg.setScaleX(cVal);
//                pubImg.setScaleY(cVal);
//                pubImg.setTranslationY(height*cVal);
//                if (cVal == 0) {
//                    llPub.setVisibility(View.GONE);
//                }
//            }
//        });
//    }
//    public void setAnimIn() {
//        ObjectAnimator anim = ObjectAnimator//
//                .ofFloat(pubImg, "yuan", 0.0F, 1.0F)//
//                .setDuration(500);//
//        anim.start();
//        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//                float cVal = (Float) animation.getAnimatedValue();
//                pubImg.setAlpha(cVal);
//                pubImg.setScaleX(cVal);
//                pubImg.setScaleY(cVal);
//                llPub.setVisibility(View.VISIBLE);
//            }
//        });
//    }

    public void setAnimOut() {
        ValueAnimator animator = ValueAnimator.ofFloat(0,llPub.getTop());
        animator.setTarget(llPub);
        animator.setDuration(500).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate(ValueAnimator animation)
            {
                Log.e("onAnimationUpdate",animation.getAnimatedValue()+"");
                llPub.setTranslationY((Float) animation.getAnimatedValue());
            }
        });
    }
    public void setAnimIn() {
        ValueAnimator animator = ValueAnimator.ofFloat(llPub.getTop(),0);
        animator.setTarget(llPub);
        animator.setDuration(500).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate(ValueAnimator animation)
            {
                Log.e("onAnimationUpdate",animation.getAnimatedValue()+"");
                llPub.setTranslationY((Float) animation.getAnimatedValue());
            }
        });
    }

    public void setDialog(){
        login = 0;
        loginDialog.setEnterPhone();
        loginDialog.show();
    }

    /**
     * 获取验证码
     * @param code
     */
    @Override
    public void getCode(String code) {

        presenter.setCode();
        loginDialog.setSmsCode(code);
    }

    @Override
    public void getType(PhoneTypeBean typeBean) {
        if (typeBean.isRegisterPhone()&&typeBean.isSetPassword()){
            if (typeBean.getMemberType().equals("2")){
                showErrorTip("此账号为司机端账号");
                loginDialog.setEnterPhone();
            }else if (typeBean.getMemberType().equals("3")){
                showErrorTip("此账号为司机端账号");
                loginDialog.setEnterPhone();
            }else{
                loginDialog.setLogin();
            }

        }else{
            if (typeBean.getMemberType().equals("2")){
                showErrorTip("此账号为司机端账号");
                loginDialog.setEnterPhone();
            }else if (typeBean.getMemberType().equals("3")){
                showErrorTip("此账号为司机端账号");
                loginDialog.setEnterPhone();
            }else{
                loginDialog.setPhotoCode();
            }
        }
    }

    @Override
    public void getUser(UserBean userBean)  {
        if (userBean == null||userBean.getId() == null){
            loginDialog.setBtn();
        }else {
            SP.putUser(MainActivity.this, userBean);
//            userPopupWindow.setData();
            loginDialog.dismiss();

            if (login == 1){
                if (userBean == null||userBean.getId() == null){

                }else {
                    SP.putUser(MainActivity.this, userBean);
                    if ((int) SP.get(this, "ApprovalStatus", 0) == 0) {
                        startActivity(new Intent(this, CertificationInformationActivity.class));
                    } else if ((int) SP.get(this, "ApprovalStatus", 0) == -1) {
                        startActivity(new Intent(this, CertificationInformationStateActivity.class));
                    } else if ((int) SP.get(this, "ApprovalStatus", 0) == 1) {
                        ToastUitl.showShort("审核中");
                    }else {
                        startActivity(PublishStrokeAddressActivity.class);
                    }
                }
            }
        }
    }

    @Override
    public void getHomeListSuccess(MainListBean bean) {
        xrecycle.refreshComplete();
        xrecycle.loadMoreComplete();

        if (bean !=null&&bean.getOrderList()!=null){
            if (pageIndex == 1){
                tvNum.setText("当前有"+bean.getTotalCount()+"辆空车");
                mainAdapter.clear();
                mainAdapter.addItems(bean.getOrderList());
            }else{
                mainAdapter.addItems(bean.getOrderList());
            }
            if (bean.getOrderList().size()>10){
                xrecycle.setLoadingMoreEnabled(false);
            }else {
                xrecycle.setLoadingMoreEnabled(true);
            }
        }
    }

    @Override
    public void setBtnCode(int index) {
        loginDialog.setBtnCode(index);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("onActivityResult","onActivityResult  "+requestCode);
        if (requestCode == 1){
//            userPopupWindow.setData();
        }
//        xrecycle.refresh();
    }

    @Override
    public void onRefresh() {
        pageIndex = 1;
        presenter.homeList(pageIndex+"","10","","0","","");
    }

    @Override
    public void onLoadMore() {
        pageIndex = pageIndex + 1;
        presenter.homeList(pageIndex+"","10","","0","","");
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (intent != null) {
            index = getIntent().getIntExtra("index", 0);
            if (index == 1){
                SP.put(this,"id","");
                setDialog();
//                userPopupWindow.dismiss();
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        xrecycle.refresh();
    }
}
